package com.liujianlei.forum_system.service.impl;

import com.liujianlei.forum_system.common.AppResult;
import com.liujianlei.forum_system.common.ResultCode;
import com.liujianlei.forum_system.dao.UserMapper;
import com.liujianlei.forum_system.exception.ApplicationException;
import com.liujianlei.forum_system.model.User;
import com.liujianlei.forum_system.service.IUserService;
import com.liujianlei.forum_system.utils.MD5Utils;
import com.liujianlei.forum_system.utils.StringUtils;
import com.liujianlei.forum_system.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author tongchen
 * @create 2023-05-28 17:31
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
  private  UserMapper userMapper;

    @Override
    public void createCommonUser(User user) {
        //空指针排除
        if(user==null){
            //日志记录错误信息
            log.error("输入的用户信息不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //从数据库中查询是否存在该数据
        User checkUser = userMapper.selectByUsername(user.getUsername());
        //存在抛出并记录日志/
        if(checkUser !=null){
            //记录日志
            log.error(ResultCode.FAILED_USER_EXISTS.toString()+"name="+checkUser.getUsername());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_USER_EXISTS));
        }
        //不存在则填充并插入数据，之后返回结果
        //补充结果
        if(user.getGender()==null) {
            //设置默认的性别
            user.setGender((byte) 2);
        }
            //设置其他值
            //设置发帖数量
            user.setPhoneNum("");
            user.setArticleCount(0);
            //设置是否为管理员
            user.setIsAdmin((byte) 0);
            //设置状态
            user.setState((byte) 0);
            //设置是否删除
            user.setDeleteState((byte) 0);
            //设置创建时间
            Date date = new Date();
            user.setCreateTime(date);
            user.setUpdateTime(date);
            //查看返回结果
            int result = userMapper.insertSelective(user);
            log.info("result="+result);
            if(result!=1){
                //记录错误日志
                log.error(ResultCode.FAILED_CREATE.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

            }
            //最终记录成功日志
            log.info("注册用户成功:"+user.getUsername());

        }

    @Override
    public User selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User login(String username, String password) {
        //判断账号密码是否为空
        if(StringUtils.isEmpty(username)&&StringUtils.isEmpty(password)){
            //打印错误的日志信息
            log.error(ResultCode.ERROR_IS_NULL.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //从数据库中查询数据
        User user = selectByUsername(username);
        if(user==null){
            //记录日志并抛出异常
            //数据库中没有该用户记录则直接报错
            //为了提高数据库的安全性，即使用户不存在，我们也返回账号或密码错误
            log.error(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //查询到比对密码
        String truePassword=user.getPassword();
        //对密码进行md5加密
        String repeatPassword= MD5Utils.md5Salt(password, user.getSalt());
        if(!repeatPassword.equals(truePassword)){
            //记录错误日志
            log.error(ResultCode.FAILED_LOGIN.toString());
            //密码错误返回报错信息
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //密码相同登陆成功，返回用户信息
        log.info("用户登录成功!");
        return user;

    }

    @Override
    public User selectByPrimaryKey(Long id) {
        //判断id是否为空
        if(id==null){
            log.error(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //调用方法
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void modifyInfo(Long id, Byte gender, String nickname, String phoneNum, String email, String remark) {
        // 非空校验，id为null 或 其他的参数全部为null
        if (id == null || (gender == null
                && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(phoneNum)
                && StringUtils.isEmpty(email)
                && StringUtils.isEmpty(remark))) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 校验用户状态
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 构造一个修改对象
        User updateUser = new User();
        // 设置Id
        updateUser.setId(id);
        // 设置昵称
        if (!StringUtils.isEmpty(nickname)) {
            updateUser.setNickname(nickname);
        }
        // 设置电话
        if (!StringUtils.isEmpty(phoneNum)) {
            updateUser.setPhoneNum(phoneNum);
        }
        // 设置邮箱
        if (!StringUtils.isEmpty(email)) {
            updateUser.setEmail(email);
        }
        // 个人简介
        if (!StringUtils.isEmpty(remark)) {
            updateUser.setRemark(remark);
        }
        // 性别
        if (gender != null && gender >= 0 && gender <= 2) {
            updateUser.setGender(gender);
        }

        // 调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_UPDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_UPDATE));
        }
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword, String passwordRepeat) {
        //判断id对应的用户是否存在
        User checkUser = userMapper.selectByPrimaryKey(id);
        //用户不存在直接报错
        if(checkUser==null){
            //记录错误信息
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //进行报错
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //如果用户存在更新信息
        //判断原密码和输入的原密码是否相同，不相同直接报错
        //对输入的密码进行加密
        String oldSalt = checkUser.getSalt();
        String realOldPassword = MD5Utils.md5Salt(oldPassword, oldSalt);
        if(!realOldPassword.equals(checkUser.getPassword())){
            log.error(ResultCode.FAILED_PASSWORD.toString());
            //报错
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PASSWORD));
        }
        //如果相同继续修改
        //创建对象并修改
        User user = new User();
        //生成加密字符
        String salt = UUIDUtils.UUID_32();
        //进行密码加密
        String realPassword = MD5Utils.md5Salt(newPassword, salt);
        //将salt存入
        user.setSalt(salt);
        user.setPassword(realPassword);
        user.setId(id);
        //修改个人信息
        int result = userMapper.updateByPrimaryKeySelective(user);
        if(result!=1){
            log.error(ResultCode.ERROR_UPDATE.toString());
            AppResult.failed(ResultCode.ERROR_UPDATE);
        }
        //生成修改成功的日志
        log.info("用户密码修改成功！" );

    }

}
